<template>
  <a-tabs v-model="activeTable" type="card" @change="changeTableByActiveTable">
    <a-tab-pane v-for="table in tables" :key="table" :tab="table">
      <!-- 数据库导入 -->
      <dataset-preview-table
        v-show="loadSuccessed"
        :head="tableData ? tableData.head : []"
        :data="tableData ? tableData.data : []"
        :data-type="'database'"
        @change-semantic="onChangeSemantic"
      />
      <p v-show="!loadSuccessed" class="load-error-msg">
        数据加载失败，<span class="reload" @click="reloadData">请重试</span>
      </p>
    </a-tab-pane>
  </a-tabs>
</template>

<script lang="ts">
/**
 * tabs used to preview all selected tables
 * @author Huihua Lu
 */
import { Component, Vue, Emit, Prop } from 'vue-property-decorator'
import DataStore from '@/store/modules/data'
import DatasetPreviewTable from '@/components/data/DatasetPreviewTable.vue'

@Component({
  components: {
    DatasetPreviewTable,
  },
})
export default class DatabaseTableTabs extends Vue {
  @Prop() databaseHeadSemantic!: any
  /* 脱敏配置传入参数 */
  @Prop() datasetData!: any
  @Prop({ type: Object, default: () => ({}) }) haveSetDesensitization!: any
  @Prop() isSetDesensitization!: any

  /** 加载状态 */
  private loadSuccessed: boolean = false

  /** 激活项 */
  public activeTable: string = ''

  // 获取当前查询信息
  public get databaseConfig() {
    return DataStore.databaseConfig
  }

  public get tables() {
    return DataStore.selectedTables
  }

  // 用于外部调用，动态配置激活table
  public setDataTable(tableName: string) {
    this.$set(this, 'activeTable', tableName)
  }

  /**
   * 加载失败， 点击 重新加载数据
   */
  public reloadData() {
    this.changeTableByActiveTable(this.activeTable)
  }

  /**
   * 根据用户的 tab 选择切换 table， 通知父组件根据当前激活的 table 更新预览数据
   */
  public changeTableByActiveTable(table: string) {
    this.$emit('change-table-by-active', table)
  }

  /**
   * 更新当前激活的表和 loading 状态（由父组件： DataUploadPage 调用）
   * @param loading
   * @param table
   */
  public updateActiveTableAndLoading(loading: boolean, table?: any) {
    this.loadSuccessed = loading
    if (table) {
      this.activeTable = table
    }
  }

  public get tableData() {
    return DataStore.selectedTableData
  }

  @Emit('change-semantic')
  public onChangeSemantic(data: any) {
    return {
      tableName: this.tableData.name,
      ...data,
    }
  }
}
</script>
